﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WeBlog.Interfaces;
using WeBlog.Repositories;

namespace WeBlog.Models {
    public class PageFormViewModel
    {        
        private readonly PageRepository _pageRepository;
        private readonly UserRepository _userRepository;

        public Page Page { get; set; }
        public IEnumerable<SelectListItem> Authors { get; private set; }

        public PageFormViewModel(IUnitOfWork unitOfwork, User user)
        {
            _pageRepository = new PageRepository(unitOfwork);
            _userRepository = new UserRepository(unitOfwork);
            Page = new Page { PublishDate = DateTime.Now };

            if (user.IsInRole(Role.Editor) || user.IsInRole(Role.Admin))
            {
                Authors = _userRepository.FindUsersInRoles(Role.Author, Role.Admin, Role.Editor, Role.Contributor)
                    .Select(x => new SelectListItem { Text = x.FullName, Value = x.UserId.ToString(), Selected = (x.UserId == (Page == null ? -1 : Page.AuthorId)) });
            }
            else
            {
                Authors = new List<SelectListItem>() { new SelectListItem { Text = user.FullName, Value = user.UserId.ToString(), Selected = true } };
            }
        }

        public PageFormViewModel(IUnitOfWork unitOfwork, int id, User user)
            : this(unitOfwork, user)
        {            
            Page = _pageRepository.Find(id);           
            if( Page == null ) throw new NotFoundException();            
        }

        public PageFormViewModel(IUnitOfWork unitOfwork, string slug, User user)
            : this(unitOfwork, user)
        {
            Page = _pageRepository.FindBySlug(slug);
            if (Page == null) throw new NotFoundException();
        }
    }
}